//我的图库
var myGallery = {
    data: {},
    uploadDir: "www/",
    imagesInfo: {page: 0, hasMore: true}, //我的图片列表
    open: function (option, callback) {
        //{layer:"#xxx",title:"我的图库"}
        var _that = this;
        this.data = option || {};
        this.data.urls = {};//所有已选图片
        this.data.max = option.max || 9;//限制选中数
        this.layer = $(option.layer);//弹出层
        this.data.multiple = option.multiple || false;//是否多选
        this.data.from = $(option.from);//图库入口元素
        this.data.change = option.change || false;//是否替换图片
        this.data.callback = option.callback || {};//使用图片时的回调
        layer.open({
            type: 1,
            title: option.title || "我的图库",
            content: this.layer,
            skin: 'layer-title',
            area: ['auto', 'auto'],
            btn: ["确定", "取消"],
            success:function(){
                $('#lay-myimg-type-ul li:nth-of-type(1)').trigger('click');
                _that.initEditTool();
            },
            yes: function () {
                _that.useImages();
            },
            btn2: function () {
                _that.close();
            },
            cancel: function () {
                _that.close();
            },
            close:function () {
            }
        });
//        $("#lay-myimg-type-ul > li").first().addClass("lay-banner-type-click").siblings().removeClass("lay-banner-type-click");
        this.getImageList();
        if (typeof callback === "function") {
            callback(option);
        }
    },
    close: function () {
        this.layer.find('.lay-banner-mask').remove();
        layer.closeAll();
        this.data = {};
    },
    getImageList: function (option) {
        option = option || {};
        var $imageUl = $("#lay-myimg-ul");
        if ($imageUl.children("li").length === 0) {
            this.imagesInfo.page = option.page = 1;
            this.requestImages(option);
        } else {
            if (option.more === true) {
                this.imagesInfo.page = option.page = this.imagesInfo.page + 1;
                this.requestImages(option);
//            } else {
//                $('#lay-myimg-ul').show().siblings().hide();
            }
        }
    },
    requestImages: function (option) {
        option.from = 'pop';//left pop
        option.rows = 16;
        editRequest.userImageList(option, {obj: myGallery, func: myGallery.showImages});
    },
    showImages: function (option) {
        if (option.more === false) {
            $('#lay-myimg-ul').show().siblings().hide();
        } else {
            $('#lay-myimg-ul').append(option.data);
        }
        if (option.more && (option.data === "" || option.data === undefined)) {
            this.imagesInfo.hasMore = false;
        }
    },
    showLatestImages: function (option) {
        var $ul = $(option.ul);
        var _list = latestImage.get();
        if (_list instanceof Array) {
            var _listHtml = '';
            for (var i in _list) {
                _listHtml += '<li class="lay-myimg-content-li" data-id="' + _list[i]['i'] + '" onclick="choseImage(this)"><img class="lay-my-img" src="' + _list[i]['u'] + '" alt=""></li>';
            }
            $ul.html(_listHtml);
        }
    },
    choseImages: function (option) {
        var $li = $(option.el);
        var _imageId = $li.data("id");
        if (this.data.urls[_imageId]) {
            delete this.data.urls[_imageId];
            $li.find(".lay-banner-mask").remove();
        } else {
            if (this.data.multiple === false) {
                this.data.urls = {};
                $li.siblings().find('.lay-banner-mask').remove();//单选
            } else {
                //计算一次已经选中的所有图片数
                var _length = 0;
                for (var i in this.data.urls) {
                    _length++;
                }
                if (_length >= this.data.max) {
                    layer.msg("最多可以选择" + this.data.max + "张图片");
                    return false;
                }
            }
            this.data.urls[_imageId] = $li.find(".lay-my-img").attr("src");
            $li.append("<img class='lay-banner-mask' src='/Public/image/www/editor/myimgclicked.png'>");
        }
    },
    useImages: function () {
        var _url = '';
        var _urlNum = 0;
        for (var _id in this.data.urls) {
            _urlNum++;
            if (this.data.change === true && this.data.multiple === false && _url == '') {
                _url = this.data.urls[_id];
            }
        }
        if(_urlNum <= 0){
            layer.msg("请至少选择一张图片");
            return false;
        }        
        try {
            if (typeof this.data.callback.func === "function") {
                var _params = {el: this.data.from[0], url: _url, urls: this.data.urls};
                $.extend(_params, this.data.callback.params || {});
                this.data.callback.func.call(this.data.callback.obj || window, _params);
            } else {
                console.log("jm：图库不知道接下去要如何处理这些选中的图片");
            }
        } catch (err) {
            console.log("jm：图库不知道接下去要如何处理这些选中的图片");
        } finally {
            latestImage.add({url: _url});
            this.close();
        }
    },
    upload: function (option, callback) {
        console.log(option.file.files);
        var _uploadMaxNum = option.num || 20;
        var _uploadMaxSize = option.size || 4194304;
        if (option.file.files.length > _uploadMaxNum) {
            layer.msg("最多只能选择" + _uploadMaxNum + "张图片");
            return false;
        }
        var _that = this;
        for (var index in option.file.files) {
            if (isNaN(index)) {
                continue;
            }
            var oneFile = option.file.files[index];
            if (oneFile.size > _uploadMaxSize) {
                layer.msg("有图片大小超过" + this.bytesToSize(_uploadMaxSize));
                return false;
            }
        }
        qiniu.getUploadToken(function (tokenResult) {
            for (var index in option.file.files) {
                if (isNaN(index)) {
                    continue;
                }
                var oneFile = option.file.files[index];
                var token = tokenResult.data.token;
                var key = _that.uploadDir + new Date().getTime() + oneFile.name;
                if (oneFile.size > 0 && token !== "") {
                    qiniu.baseUpload(oneFile, token, key, _that.uploadCallback, {tokenResult: tokenResult, oneFile: oneFile, callback: callback});
                }
            }
            option.file.value = "";//支持可以再次上传相同文件
        });
    },
    uploadCallback: function (uploadResult, extend) {
        //{hash: "FqEijjiNdNVtMmQdd7D3ZcE8Vw3s", key: "www/1497489877490huodongju-logo.png", state: 1}
        if (uploadResult.state === 1) {
            var _url = extend.tokenResult.data.domain + uploadResult.key + "?imageslim";
            try {
                if (typeof extend.callback.func === "function") {
                    var _params = {uploadResult: uploadResult, url: _url};
                    $.extend(extend.callback.params || {}, _params);
                    editRequest.addUserImage({key: uploadResult.key},extend.callback);
                }
                layer.msg('上传成功');
            } catch (err) {
                console.log("上传图片成功后异常:" + err);
                layer.msg('上传失败');
                return false;
            }
        } else {
            layer.msg(extend.oneFile.name + '上传失败');
            return false;
        }
    },
    addToPopGallery: function (option) {
        //默认弹窗图库处理   
        var _imageLiHtml = '<li class="lay-myimg-content-li" data-id="' + option.id + '" onclick="choseImage(this)">' +
                '<img class="lay-my-img" src="' + option.url + '" alt="">' +
                '</li>';
        $("#lay-myimg-ul").prepend(_imageLiHtml);
        $("#lay-myimg-ul").children("li").first().trigger("click");
        //左侧
        if($("#com-left-gallery-section > div").length > 0){
            var _liHtml = '<div class="com-gallery com-item" data-id="' + option.id + '" data-key="' + option.uploadResult.key + '">' +
                                '<div class="com-content">'+
                                    '<img src="' + option.url + '" alt="">'+
                                '</div>'+
                                '<div class="com-delete-myimg">'+
                                    '<span>×</span>'+
                                '</div>'+
                            '</div>';
            $("#com-left-gallery-section").prepend(_liHtml);
        }
    },
    addToLeftGallery: function (option) {
        //左侧
        var _liHtml = '<div class="com-gallery com-item" data-id="' + option.id + '" data-key="' + option.uploadResult.key + '">' +
                            '<div class="com-content">'+
                                '<img src="' + option.url + '" alt="">'+
                            '</div>'+
                            '<div class="com-delete-myimg">'+
                                '<span>×</span>'+
                            '</div>'+
                        '</div>';
        $("#com-left-gallery-section").prepend(_liHtml);
        //默认弹窗图库处理   
        if($("#lay-myimg-ul > li").length > 0){
            var _imageLiHtml = '<li class="lay-myimg-content-li" data-id="' + option.id + '" onclick="choseImage(this)">' +
                    '<img class="lay-my-img" src="' + option.url + '" alt="">' +
                    '</li>';
            $("#lay-myimg-ul").prepend(_imageLiHtml);
        }
    },
    bytesToSize: function (bytes) {
        if (bytes === 0)
            return '0 B';
        var k = 1024, // or 1024  
                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    },
    initEditTool:function(){
        $('.lay-myimg-edit').show();                
        
        var $editBtn = $("#lay-myimg-edit-btn");
        $editBtn.text('编辑');
        $editBtn.attr('data-type','0');
        
        var $li = $('.lay-myimg-content-li');
        $li.attr('onclick','choseImage(this)').find('.lay-banner-mask').remove();
        
        $('.myimg-edit-box').hide();
        $(".layui-layer-btn>a").show();
    },
    openEditTool:function(){
        $('.lay-myimg-edit').show(); 
        
        var $editBtn = $("#lay-myimg-edit-btn");
        $editBtn.text('退出编辑');
        $editBtn.attr('data-type','1');
        
        var $li = $('.lay-myimg-content-li');
        $li.attr('data-chose','0');
        $li.attr('onclick','myGallery.chooseOne(this);').find('.lay-banner-mask').remove();        
        
        var $myImgEditBox = $('.myimg-edit-box');
        $myImgEditBox.children(".myimg-edit-all").attr("data-type",0);
        $myImgEditBox.find('.fa').removeClass('fa-check-square').addClass('fa-square-o');
        $myImgEditBox.show();
        $(".layui-layer-btn>a").hide();
    },
    edit:function (_this) {
        var _type = $(_this).attr('data-type');        
        if(_type == '0'){//进入编辑
            this.openEditTool();
        }else if(_type == '1'){//退出编辑
            this.initEditTool();
        }
    },
    chooseAll:function (_this) {
        var $li = $('.lay-myimg-content-li');
        var _type = $(_this).attr('data-type');
        if(_type == '0'){
            $(_this).find('.fa').removeClass('fa-square-o').addClass('fa-check-square');
            $(_this).attr('data-type','1');
            $li.append("<img class='lay-banner-mask' src='/Public/image/www/editor/myimgclicked.png'>");
            $li.attr('data-chose','1');

        }else if(_type == '1'){
            $(_this).find('.fa').removeClass('fa-check-square').addClass('fa-square-o');
            $(_this).attr('data-type','0');
            $li.find('.lay-banner-mask').remove();
            $li.attr('data-chose','0');
        }
    },
    chooseOne:function (_this) {
        var _type = $(_this).attr('data-chose');
        if(_type == '1'){
            $(_this).find('.lay-banner-mask').remove();
            $(_this).attr('data-chose','0');
        }else if(_type == '0'){
            $(_this).append("<img class='lay-banner-mask' src='/Public/image/www/editor/myimgclicked.png'>");
            $(_this).attr('data-chose','1');
        }
    },
    delete:function () {
        var $lis = $('.lay-myimg-content-li[data-chose="1"]');
        var _ids = "";
        var _idsArr = [];
        var _that = this;
        $lis.each(function(i){
            _ids += $(this).data("id") + ",";
            _idsArr.push($(this).data("id"));
        });
        if (_ids != ''){
            layer.confirm("确定要删除吗",
                    {
                        area:['265px','auto'],
                        btn: ['确定', '取消'],
                        skin:'lay-delete',
                        title:false,
                        closeBtn:false,
                        content:'确定要删除吗？'
                    },
                    function (index) {
                        editRequest.delUserImage({id: _ids, key: ""});
                        $lis.remove();
                        _that.deleteLeftImage(_idsArr);
                        layer.close(index);
                        layer.msg('删除成功');
                        $("#lay-myimg-edit-btn").trigger("click");
                    }, function () {
                        return true;
                    }
            );            
        }else {
            layer.msg('请选择要删除的图片');
        }
    },
    deleteLeftImage:function(_idsArr){
        for(var i in _idsArr){
            $("#com-left-gallery-section").children("div[data-id='" + _idsArr[i] + "']").remove();
        }
    }
};

//裁剪弹窗
var myCrop = {
    data: {},
    jcropApi: null,
    cropImage: null, //裁剪框image标签对象
    //打开裁剪框
    open: function (option, layerConfig, jcropConfig) {
        layerConfig = layerConfig || {};
        jcropConfig = jcropConfig || {};
        this.data = option || {};
        this.data.callback = option.callback || {};//使用裁剪图片时的回调
        this.data.from = option.el;
        this.cropImage = $(option.selector || "#imghead");
        if (option.toupload !== true) {
            //toupload：裁剪后要上传图片
            this.data.url = $(option.el).parent("div").siblings('img').first().attr('src');//@todo考虑放在外面
            this.cropImage.attr('src', this.data.url);
        }
        var _that = this;

        //弹出层
        var _layerConfig = {
            type: 1,
            title: option.title || "图片裁剪",
            content: $(option.layer) || $("#lay-banner-upload"),
            closeBtn: 2,
            skin: 'layer-title',
            area: ['auto', 'auto'],
            btn: ["确定", "取消"],
            yes: function () {
                _that.useCrop();
            },
            btn2: function () {
                _that.close();
                $('#banner-upload').val('');
            },
            cancel: function () {
                _that.close();
            }
        };
        $.extend(_layerConfig, layerConfig);
        layer.open(_layerConfig);
        //裁剪框
        var _jcropConfig = {
            setSelect: [113, 87, 482, 296]
//            allowSelect: true,
//            aspectRatio: 19 / 9,
//            minSize: [453, 256]
        };
        $.extend(_jcropConfig, jcropConfig);
        this.cropImage.Jcrop(_jcropConfig, function () {
            _that.jcropApi = this;
            //使得图片在裁剪框中居中
            var _height = $('.jcrop-holder').height();
            $('.jcrop-holder').css('top',('430' - _height) / '2');
        });
    },
    close: function () {
        if (this.jcropApi !== null) {
            this.jcropApi.destroy();
        }
        layer.closeAll();
        this.cropImage.attr("src", "").css({width: "auto", height: "auto"});//解决再次进入裁剪 宽高问题
        this.cropImage = null;
        this.data = {};
    },
    //使用裁剪
    useCrop: function () {
        var scale = this.getCropScale();
        var coord = this.getCoord();
        var _newUrl = '';
        if (this.data.toupload !== true) {
            var _symbol = "?", _params = "";
            if (this.data.url.indexOf("?") > 0) {
                _params = this.data.url.substring(this.data.url.indexOf("?") + 1, this.data.url.length);
                if (_params !== "") {
                    _symbol = "&";
                }
            }
            _newUrl = this.data.url + _symbol + "imageMogr2/auto-orient/crop/!" + parseInt(coord.w / scale[0]) + "x"
                    + parseInt(coord.h / scale[1]) + "a"
                    + parseInt(coord.x / scale[0]) + "a"
                    + parseInt(coord.y / scale[1]);
        }
        if (typeof this.data.callback.func === "function") {
            editRequest.catcheImg({url:_newUrl},{obj:this.data.callback.obj,func:this.data.callback.func,params:{el: this.data.from, scale: scale, coord: coord}});
//            this.data.callback.func.call(this.data.callback.obj || window, {el: this.data.from, url: _newUrl, scale: scale, coord: coord});
        } else {
            console.log("jm：接下去要如何处理这些裁剪的图片");
        }
        this.close();
    },
    //获取选框的值（界面尺寸）
    getCoord: function () {
        var coord = this.jcropApi.tellScaled();
        return coord;
    },
    //计算缩放比例
    getCropScale: function () {
        var jcropWidth = this.jcropApi.getWidgetSize()[0];
        var jcropHeight = this.jcropApi.getWidgetSize()[1];

        if (this.data.toupload === true) {
            var fullWidth = this.data.trueWidth;
            var fullHeight = this.data.trueHeight;
        } else {
            var _image = new Image();
            _image.src = this.data.url;
            var fullWidth = _image.width;
            var fullHeight = _image.height;
        }

        var scaleWidth = jcropWidth / fullWidth;
        var scaleHeight = jcropHeight / fullHeight;

        var scale = [];
        scale[0] = scaleWidth;
        scale[1] = scaleHeight;
        return scale;
    }


};

//快捷组件  视频弹窗
var myVideo = {
    data: {},
    open: function (option) {
        //{layer:"#xxx",title:"我的xx"}
        this.data = option || {};
        this.layer = $(option.layer || "#lay-myvideo-box");//弹出层
        this.data.from = $(option.from);//图库入口元素
        this.data.callback = option.callback || {};//使用图片时的回调   
        var _that = this;
        layer.open({
            type: 1,
            title: "插入视频",
            content: this.layer,
            skin: 'layer-title',
            area: ['auto', 'auto'],
            btn: ["确定", "取消"],
            yes: function (index, layer) {
                _that.useVideo();
            },
            btn2: function () {
                _that.close();
            },
            cancel: function () {
                _that.close();
            }
        });
    },
    close: function () {
        layer.closeAll();
        this.data = {};
    },
    useVideo: function (option) {
        var _input = this.layer.find("textarea").val();
        var _baseCom = new BaseCom();
        var _text = _baseCom.filterSensitiveString(_input);
        var _res = _baseCom.dealVideoSrc(_text);
        if (_res.code === 1) {
            _text = _res.content;
        } else {
            var $videoError = this.layer.find("div.edit-video-error");
            $videoError.children("span").eq(1).html(_res.content);
            $videoError.show();
            layer.msg(_res.content);
            return false;
        }
        if (typeof this.data.callback.func === "function") {
            var _params = {el: this.data.from[0], text: _text, input:_input};
            $.extend(_params, this.data.callback.params);
            this.data.callback.func.call(this.data.callback.obj || this, _params);
        } else {
            console.log("jm：接下去不知道要如何处理这个视频");
        }
        this.close();
    }

};

//最近使用图片
var latestImage = {
    max: 20, //最多存储
    add: function (option) {
        var _userId = $("#userId").val();
        var _images = localStorage["hdjLatestImages_" + _userId];
//        var _images = localStorage.hdjLatestImages;
        if (_images !== '' && _images !== undefined) {
            var _imagesArr = JSON.parse(_images);
        }
        var _size = 0;
        if (_imagesArr instanceof Array) {
            for (var i in _imagesArr) {
                if (_imagesArr[i]['u'] == option.url) {
                    _imagesArr.splice(i, 1);
                } else {
                    _size++;
                }
            }
            if (_size >= this.max) {
                _imagesArr.pop();
            }
        } else {
            _imagesArr = [];
        }
        option.id = 'late_' + Date.now().toString() + Math.floor(Math.random() * 100);
        _imagesArr.unshift({i: option.id, u: option.url});
        localStorage["hdjLatestImages_" + _userId] = JSON.stringify(_imagesArr);
//        localStorage.hdjLatestImages = JSON.stringify(_imagesArr);
    },
    get: function () {
        var _userId = $("#userId").val();
        var _images = localStorage["hdjLatestImages_" + _userId];
//        var _images = localStorage.hdjLatestImages;
        var _imagesArr = [];
        if (_images !== '' && _images !== undefined) {
            _imagesArr = JSON.parse(_images);
        }
        return _imagesArr;
    },
    //清空
    empty:function(){
        var _userId = $("#userId").val();
        $('#lay-lately-ul>li').remove();
        localStorage["hdjLatestImages_" + _userId] = '';
        layer.msg('清除成功');
    }
};